<script setup>
import { reactive, ref, watch } from "vue";
import {
  Search,
  DeleteFilled,
  WarningFilled,
  Promotion,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import AddNewDialog from "./AddNewDialog";
import DefineFeatureTargetDialog from "./DefineFeatureTargetDialog.vue";
import XLSX from "xlsx";
import {
  getSrcDataList,
  deleleSrcData,
  getSrcDataByFileName,
  uploadMetaDataList,
  getMetaDataList,
} from "@/views/DataManagement/api.js";
let visitable = ref(false);
// 打开新建窗口
const addNew = () => {
  visitable.value = true;
};
// 导出excel
const exportExcel = () => {
  const data = XLSX.utils.json_to_sheet(tableDataRight.value); //此处tableData.value为表格的数据
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, data, "data"); //test-data为自定义的sheet表名
  XLSX.writeFile(wb, "test.xlsx"); //test.xlsx为自定义的文件名
  // console.log("导出成功");
};
// 关闭新建窗口
const handleClose = () => {
  visitable.value = false;
};
// 在左侧列表添加当前数据
let tableDataLeft = ref([
  // {
  // projectName:'地方'
  // }
]);
// 后台请求左侧列表数据并处理
// getSrcDataList().then((res) => {
//   res.data.databaseList.forEach((item) => {
//     tableDataLeft.push({ projectName: item });
//   });
//   console.log("tableDataLeft", tableDataLeft);
// });
let currentSrcProjectName = ref("");

getSrcDataList()
  .then((res) => {
    const temArray = reactive([]);
    res.data.databaseList.forEach((item) => {
      temArray.push({ projectName: item });
    });
    // console.log("临时数组", temArray);
    tableDataLeft.value = temArray;
    // 设置当前项目名称为列表中的第一个
    currentSrcProjectName.value = tableDataLeft.value[0].projectName;
    // console.log('当前项目名',currentSrcProjectName.value)
    // console.log("tableDataLeft", tableDataLeft.value [0]);
    // 将列表第一个文件数据加载到右侧表格
    loading.value = true;
    getSrcDataByFileName({
      excel_name: tableDataLeft.value[0].projectName,
    }).then((res) => {
      tableDataRight.value = res.data.srcDataJson;
      // console.log(res.data.srcDataJson)
      loading.value = false;
    });
  })
  .catch((res) => {
    console.log("报错", res);
  });
// 右侧列表数据

let tableDataRight = ref([]);
let columnNames = ref([]);
// const columnNames = computed(()=>tableDataRight[0].keys())
// 拿到上传数据事件
const getUploadData = (param) => {
  // console.log("父组件拿到数据", param.name);
  tableDataLeft.value.unshift({ projectName: param.name });
  tableDataRight.value = param.data;
  // console.log("父组件拿到数据", tableDataRight.value);
  //   console.log(tableDataRight[0])
};
watch(tableDataRight, (newValue) => {
  // console.log("监听到了");
  columnNames.value = [];
  Object.keys(newValue[0]).forEach((item) => {
    let columnObject = {
      key: item,
      dataKey: item,
      title: item,
      width: 150,
    };
    columnNames.value.push(columnObject);
  });
  //   columnNames.value = Object.keys(newValue[0]);

  columnData.value = Object.keys(newValue[0]);
  // console.log("列名", columnData.value);
});

// 选择特征标签列事件
let visitedfeatureSelect = ref(false);
let columnData = ref([]);

const selectFeatureTabel = () => {
  // console.log("jinru");
  visitedfeatureSelect.value = true;
};
const closeSelect = () => {
  // console.log('子传父事件')
  visitedfeatureSelect.value = false;
};
// 删除左侧列表内容事件
const handleDelet = (item) => {
  deleleSrcData({ delete_excel_name: item.projectName }).then((res) => {
    ElMessage({
      message: res.data.message,
      type: "success",
    });
  });
  // 每次删除后更新数据左侧数据列表

  getSrcDataList().then((res) => {
    let temArray = [];
    res.data.databaseList.forEach((item) => {
      temArray.push({ projectName: item });
    });
    tableDataLeft.value = temArray;
  });
};
// 点击左侧数据表名获取详细数据赋值给tableDataRight

const loading = ref(false);
const selectProject = (item) => {
  loading.value = true;
  getSrcDataByFileName({ excel_name: item.projectName }).then((res) => {
    tableDataRight.value = res.data.srcDataJson;
    loading.value = false;
  });
  currentSrcProjectName.value = item.projectName;
  console.log("当前项目名", currentSrcProjectName.value);
};
// 拿到声明特征标签的数据
const getSelectResult = (selectResult) => {
  // console.log(selectResult[0])
  let formulaArr = selectResult[0].selectChemicalFormula;
  let featuresArr = selectResult[0].selectFeatures;
  let targetArr = selectResult[0].selectTarget;
  let selectColArr = formulaArr.concat(featuresArr, targetArr);
  // 将选中的列展示在右侧列表作为元数据的预览
  let temRightData = [];
  tableDataRight.value.forEach((obj) => {
    let temObj = {};
    selectColArr.forEach((col) => {
      temObj[col] = obj[col];
    });
    temRightData.push(temObj);
  });
  tableDataRight.value = temRightData;
  // 流转到元数据库按钮开启
  emitToMeta.value = false;
};

// 流转到元数据库
let emitToMeta = ref(true);
const handleEmitToMeta = async () => {
  // 流传前做同名文件判断
  let res = await getMetaDataList();
  // console.log('元数据列表名1',res.data.databaseList)
  // console.log('元数据列表名2',currentSrcProjectName.value+'_元数据')
  if (
    res.data.databaseList.indexOf(currentSrcProjectName.value + "_元数据") >= 0
  ) {
    // console.log("覆盖");
    ElMessage({
      message: "元数据存在同名文件，已覆盖！",
      type: "success",
    });
  }
  loading.value = true;

  uploadMetaDataList({
    json_list: tableDataRight.value,
    excel_name: currentSrcProjectName.value + "_元数据",
  })
    .then((res) => {
      ElMessage({
        message: res.data.message,
        type: "success",
      });
      // 成功后就关闭流转到元数据的按钮
      emitToMeta.value = true;
    })
    .catch((res) => {
      ElMessage({
        message: "上传失败！",
        type: "warning",
      });
      console.log("失败原因：", res);
    });
  loading.value = false;
};
</script>
<template>
  <div class="srcData-Wrap">
    <!-- 左侧折叠面板 -->
    <div class="left-table">
      <el-card class="search-card">
        <!-- 左侧搜索框 -->
        <el-input
          class="input-search"
          v-model="searchContent"
          placeholder="输入关键词"
          clearable
        />
        <el-button
          class="butt-search"
          :icon="Search"
          @click="handerSearchFist"
          circle
        />

        <!-- 新建按钮 -->
        <div class="btns">
          <el-button class="butt-newBuilt" type="success" @click="addNew"
            >新建</el-button
          >
          <el-button class="butt-analyze" type="success">分析</el-button>
          <el-button
            class="butt-exportExcel"
            type="success"
            @click="exportExcel"
            >导出Excel</el-button
          >
        </div>
        <div
          style="
             {
              width: 300px;
              height: 1px;
              background-color: rgb(151, 151, 151);
              margin-top: 10px;
            }
          "
        ></div>
        <ul class="projectlist">
          <h3>数据表名称</h3>

          <li
            v-for="(item, index) in tableDataLeft"
            :key="item.projectName"
            :title="item.projectName"
            :tabindex="index + 1"
            @click="selectProject(item)"
          >
            <span>{{ index + 1 }}. {{ item.projectName }}</span>
            <el-popconfirm
              title="确认删除? 谨慎操作！"
              @confirm="handleDelet(item)"
            >
              <template #reference>
                <i>
                  <el-icon title="删除"><DeleteFilled /></el-icon>
                </i>
              </template>
            </el-popconfirm>
          </li>
        </ul>
      </el-card>
    </div>
    <!-- 列表部分 -->

    <div class="search-newBuilt">
      <!-- 右侧子表格部分 -->
      <div class="leftTale-Operation">
        
          <el-popconfirm
            title="确认删除? 谨慎操作！"
            @confirm="handleEmitToMeta"
          >
            <template #reference>
              <el-tooltip class="box-item" effect="dark" placement="top-start">
          <template #content>
            将声明特征和标签后的数据流转存入元数据库进行管理<br />注意：元文件名=源文件名_元数据，元数据库已有的同名文件将被覆盖！
          </template>
              <el-button
                class="btn-emitMetaBD"
                type="success"
                link
                :disabled="emitToMeta"
                >流转到元数据库<el-icon><Promotion /></el-icon
              ></el-button>
              </el-tooltip>
            </template>
          </el-popconfirm>
        

        <span id="warnSpan"
          >表格仅用于预览，复杂操作请用Excel进行以保证性能！</span
        >
        <el-tooltip class="box-item" effect="dark" placement="top-start">
          <template #content>
            通过列选择的方式声明特征输入和标签输出<br />注意：必选一个化学式输入！
          </template>
          <el-button
            class="btn-defineFeatureTarget"
            type="success"
            link
            @click="selectFeatureTabel"
            >声明特征和标签列<el-icon><WarningFilled /></el-icon
          ></el-button>
        </el-tooltip>
        <!-- 特征选择子组件 -->
        <DefineFeatureTargetDialog
          :visitedfeatureSelect="visitedfeatureSelect"
          :columnData="columnData"
          @closeSelect="closeSelect"
          @getSelectResult="getSelectResult"
        ></DefineFeatureTargetDialog>
      </div>

      <el-card ref="leftTableCard" class="table">
        <el-table-v2
          v-loading="loading"
          class="tabel-content"
          :columns="columnNames"
          :data="tableDataRight"
          :width="1100"
          :height="500"
          fixed
        />
      </el-card>
    </div>
  </div>
  <AddNewDialog
    :visitable="visitable"
    :tableDataLeft="tableDataLeft"
    @handleClose="handleClose"
    @getUploadData="getUploadData"
  ></AddNewDialog>
</template>
<style lang="less" scoped>
.srcData-Wrap {
  display: flex;
  .left-table {
    width: 300px;
    .search-card {
      position: relative;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-bottom: 10px;
      width: 300;
      height: 560px;

      .input-search {
        width: 200px;
        height: 40px;
      }
      .butt-search {
        margin-left: 10px;
      }
      .btns {
        display: flex;
        padding-top: 10px;
      }
      .butt-newBuilt {
        // margin: 10px;
        //    margin-left:0;
      }
      .butt-analyze {
        margin-left: 10px;
      }
    }
  }
  .search-newBuilt {
    flex: 1;
    padding-left: 10px;
    el-icon {
      float: right;
    }
    .btn-defineFeatureTarget {
      float: left;
    }
    .btn-emitMetaBD {
      float: right;
    }
  }
  .projectlist {
    // width: 250px;
    list-style-type: none;
    margin: 0;
    padding: 0;

    > li {
      position: relative;
      height: 30px;
      line-height: 30px;
      border-radius: 5%;
    }

    > li i {
      position: absolute;
      display: none;
      text-align: right;
      bottom: 4px;
    }
  }
  .projectlist > li:hover span {
    font-size: 17px;
    cursor: pointer;
  }
  .projectlist > li:hover i {
    display: inline-block;
  }
  .projectlist > li i:hover {
    display: inline-block;
    font-size: 17px;
    cursor: pointer;
  }

  .projectlist > li:focus {
    font-size: 17px;
    background-color: rgba(213, 235, 245, 0.56);
  }

  .projectlist > li {
    width: 270px;

    text-align: left;
    margin-bottom: 7px;
    > span {
      width: 250px;
      white-space: nowrap;
      text-overflow: ellipsis;

      overflow: hidden;
      display: inline-block;
    }
  }
}
</style>
